package com.youdianstar.app.service

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import android.os.Handler
import android.os.Message
import androidx.core.app.NotificationCompat
import com.youdianstar.app.R
import com.youdianstar.app.ui.MainActivity
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.Topic
import com.youdianstar.app.common.entity.BusEntity
import com.youdianstar.app.common.util.LogUtil
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.safframework.eventbus.EventBus


/**
 * File: BrsMessagingService
 * Author: 82149 Create: 2021/12/3 16:21
 * Changes (from 2021/12/3)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class BrsMessagingService : FirebaseMessagingService(){
    companion object {
        private const val TAG = "BrsMessagingService"
    }

    @SuppressLint("HandlerLeak")
    var handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                val remoteMessage = msg.obj as RemoteMessage
                val data = remoteMessage.data
                val notification = remoteMessage.notification
                val body = notification?.body
                val title = notification?.title
                var type:String? = null
                var msgStr:String? = null
                LogUtil.i("---receiver:$title")
                //EventBus.post(BusEntity(DataCode.PUSH_EVENT),100L)
                if (data.isNotEmpty()){
                    val datas = remoteMessage.data
                    type = datas[Topic.MSGTYPE]
                    msgStr = datas[Topic.MSG]
                    LogUtil.d("push",data.toString())
                    when(type){
                        Topic.EVENT_ORDER_PAY,Topic.EVENT_LOSS_PAY->{
                            val json = datas[Topic.DATA]
                            LogUtil.d("pushJson", "----data:$json")
                            EventBus.post(BusEntity(DataCode.ORDER_FINISH),100L)
                        }
                        Topic.EVENT_POWER_RP->{
                            msgStr = datas[Topic.BRANCH]
                            val address  = datas[Topic.ADDRESS]
                            LogUtil.d("pushJson", "----id:$msgStr;address:$address")
                            //showLowPowerDialog(title,body,msgStr,address)
                            return
                        }
                        else->{

                        }
                    }
                }
                sendNotification( title,body, type, msgStr)
            }
        }
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        val message = handler.obtainMessage()
        message.what = 1
        message.obj = remoteMessage
        handler.sendMessage(message)
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        LogUtil.d("---Firebase token : $token")
        //sendRegistrationToServer(token)
    }


    /**
     * Create notification
     *
     * @param messageBody FCM message body received.
     */
    private fun sendNotification(titleStr :String?,messageBody: String?,type: String?,msgStr: String?) {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(this, 0 , intent, PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE)

        val channelId = getString(R.string.default_notification_channel_id)
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.icon_logo)
            .setContentTitle(titleStr?:"")
            .setContentText(messageBody?:"")
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
    }
}